package com.kfm.servlet;

import com.kfm.dao.UserDao;
import com.kfm.model.User;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置获取请求的流的编码
        req.setCharacterEncoding("utf-8");
        // 设置响应流的编码
        resp.setCharacterEncoding("UTF-8");
        // 设置浏览器如何去渲染响应的内容
        resp.setContentType("text/html;charset=utf-8");
        // 获取请求参数
        // 判断验证码
        String verCode = req.getParameter("verCode");
        // 判断验证码是否正确
        boolean ver = CaptchaUtil.ver(verCode, req);
        if (ver) {

            String password = req.getParameter("password");
            String confirmPassword = req.getParameter("confirm_password");
            // 验证重复密码是否一致
            if (password != null && !password.isEmpty() && password.equals(confirmPassword)) {
                String username = req.getParameter("username");
                String email = req.getParameter("email");
                if (username != null && !username.isEmpty()) {
                    User user = new User();
                    user.setName(username);
                    user.setPassword(password);
                    user.setEmail(email);
                    // 向数据库插入数据
                    int add = userDao.add(user);
                    if (add > 0) {
                        System.out.println("注册成功");
                        resp.getWriter().write("<h3>恭喜，注册成功！</h3>");
                    } else {
                        System.out.println("注册失败");
                        resp.getWriter().write("<h3>注册失败！</h3>");
                    }
                }
            }
        } else {
            System.out.println("验证码错误");
            resp.getWriter().write("<h3>验证码错误</h3>");
        }
    }
}
